<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

/**
 * @OA\Tag(
 *      name="Auth",
 *      description="用户鉴权",
 * )
 */

class AuthController extends Controller
{
    /**
     * @OA\Post(
     *      path="/api/register",
     *      summary="用户注册",
     *      tags={"Auth"},
     *      @OA\RequestBody(
     *          required=true,
     *          @OA\JsonContent(
     *              required={"name","email","password"},
     *              @OA\Property(property="name", type="string", example="John Doe"),
     *              @OA\Property(property="email", type="string", format="email", example="johndoe@example.com"),
     *              @OA\Property(property="password", type="string", format="password", example="12345678")
     *          ),
     *      ),
     *      @OA\Response(
     *          response=201,
     *          description="注册成功",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *              @OA\Property(property="user_id", type="integer", example=1),
     *          )
     *      ),
     *      @OA\Response(
     *          response=409,
     *          description="用户已存在",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *              @OA\Property(property="user_id", type="integer", example=1),
     *          )
     *      ),
     *
     * )
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|max:255',
            'password' => 'required|string|min:6',
        ]);

        Log::debug(sprintf("register start | register=%s", $request->name));

        // 检查用户是否已存在
        $existingUser = User::where('email', $request->email)->first();
        if ($existingUser) {

            // $credentials = $request->only('email', 'password');
            // if (!$token = JWTAuth::attempt($credentials)) {
            //     return response()->json(['error' => 'Unauthorized'], 401);
            // }

            // printf("token=%s\n", $token);

            // 如果用户已存在，返回错误提示
            return response()->json(['message' => 'User already exists'], 409);
        }

        // 创建新用户
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        // 接口逻辑代码
        $data = ['status' => 'success', 'message' => 'exec ok'];
        header('Content-Type: application/json');

        Log::debug(sprintf("data=%s", json_encode($data)));

        Log::debug(sprintf("register ok"));
        return response()->json(['message' => 'OK', 'user_id' => $user->id], 201);
    }

    /**
     * @OA\Post(
     *      path="/api/login",
     *      summary="用户登录",
     *      tags={"Auth"},
     *      @OA\RequestBody(
     *          required=true,
     *          @OA\JsonContent(
     *              required={"email","password"},
     *              @OA\Property(property="email", type="string", format="email", example="johndoe@example.com"),
     *              @OA\Property(property="password", type="string", format="password", example="12345678")
     *          ),
     *      ),
     *      @OA\Response(
     *          response=200,
     *          description="执行成功",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *              @OA\Property(property="token", type="string", example="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMy4..."),
     *          )
     *      ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *          )
     *     ),
     * )
     */
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json(['message' => 'Unauthorized',], 401);
        }

        LOG::debug(sprintf("login ok|token=%s\n", $token));
        return response()->json(['message' => 'OK', 'token' => $token], 200);
    }

    /**
     * @OA\Get(
     *     path="/api/user",
     *     tags={"Auth"},
     *     summary="用户信息查询",
     *     description="用email查对应的用户信息，如果email地址为空，则查自己的用户信息",
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="email",
     *         in="query",
     *         description="用户的邮箱地址；  空值，表示查自己的信息； 非空值，查别人的信息",
     *         required=false,
     *         @OA\Schema(type="string", format="email", example="johndoe@example.com")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="执行成功",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *              @OA\Property(property="reqEmail", type="string", example="johndoe0@example.com", description="空值，查自己的信息； 非空值，查别人的信息"),
     *              @OA\Property(property="user_id", type="integer", example=1),
     *              @OA\Property(property="name", type="string", example="johndoe"),
     *              @OA\Property(property="email", type="string", example="johndoe@example.com"),
     *          )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="用户不存在",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *          )
     *     ),
     * )
     */

    public function getUser(Request $request)
    {
        $currMail = null;
        $user = auth()->user();
        if ($request->email === null || $request->email === "") {
            $currMail = $user->email;
        } else {
            $request->validate([
                'email' => 'required|string',
            ]);
            $currMail = $request->email;
        }

        LOG::debug(sprintf("getUser start|currMail=%s\n", $currMail));

        // 检查用户是否已存在
        $existingUser = User::where('email', $currMail)->first();
        if (!$existingUser) {
            return response()->json(['message' => 'User not found'], 404);
        }

        LOG::debug(sprintf("getUser, found|existingUser=%s\n", $existingUser));
        return response()->json(['message' => 'ok', 'reqMail' => $request->email, "user_id" => $existingUser->id, "name" => $existingUser->name, "email" => $existingUser->email], 200);
    }

    /**
     * @OA\Post(
     *      path="/api/user",
     *      summary="更新用户信息",
     *     description="当前仅能更新 用户名称",
     *      tags={"Auth"},
     *      security={{"bearerAuth":{}}},
     *      @OA\RequestBody(
     *          required=true,
     *          @OA\JsonContent(
     *              required={"name"},
     *              @OA\Property(property="name", type="string", example="johndoe")
     *          ),
     *      ),
     *      @OA\Response(
     *          response=200,
     *          description="执行成功",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *              @OA\Property(property="newName", type="string", example="johndoe1", description="更新后的 name"),
     *          )
     *      ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="数据不存在（用户不存在）",
     *          @OA\JsonContent(
     *              @OA\Property(property="message", type="string", example="OK"),
     *          )
     *     ),
     * )
     */
    public function updateProfile(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
        ]);

        $user = auth()->user();

        LOG::debug(sprintf("updateProfile start||user=%s|name=%s\n", json_encode($user), $request->name));

        $user->update(['name' => $request->name]);

        LOG::debug(sprintf("updateProfile||user=%s\n", json_encode($user)));
        return response()->json(['message' => 'OK', 'newName' => $user->name], 200);
    }
}
